package com.ruoyi.demowechatpay.service;


import com.ruoyi.demowechatpay.enumeration.ServiceEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 业务单号管理器
 * 主要用于生成唯一的业务单号
 *
 * @author wulongcha
 * @date 2021/2/5 1:40 下午
 */
@Component
public class BusinessNumberManager {

    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneId.systemDefault());
    private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmssSSS").withZone(ZoneId.systemDefault());

    private static String serviceName;

    @Value("${spring.application.name}")
    public void setServiceName(String name) {
        serviceName = name;
    }

    public static String generateShortV2(String businessType) {
        if (StringUtils.isEmpty(businessType)) {
            throw new RuntimeException("业务类型不能为空");
        }

        Instant now = Instant.now();
        return businessType + encode(getTimeString(now) + getRandomString() + ServiceEnum.fullNameOf(serviceName).getCode());
    }

    private static String encode(String originNumber) {
        return Long.toString(Long.parseLong(originNumber), 36).toUpperCase();
    }

    private static String getTimeString(Instant instant) {
        return timeFormatter.format(instant);
    }

    private static String getRandomString() {
        return String.valueOf(ThreadLocalRandom.current().nextInt(900) + 100);
    }


}
